"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Fixed
Case Name   : fixed类型支持创建MOT表
Create At   : 2022/03/21
Owner       : @li-xin12345
Description :
    1. 创建兼容B库，检查dolphin插件
    2. 设置enable_incremental_checkpoint=off
    3. 创建mot表含fixed类型并插入数据
    4. 查询数据
    5. 恢复环境
Expect      :
    1. 创建成功，插件自动加载
    2. 设置成功
    3. 创建成功
    4. 查询成功
    5. 恢复成功
History     :
"""

import os
import unittest

from yat.test import Node
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common


class MotSupportFixed(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.user = Node('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.commonsh = CommonSH('PrimaryDbUser')
        status = self.commonsh.get_db_cluster_status("detail")
        self.log.info(status)
        self.assertTrue("Normal" in status or "Degraded" in status)
        self.db_name = 'db_fixed_024'
        self.tb_name = 't_fixed_024'
        self.default_vales = self.common.show_param(
            'enable_incremental_checkpoint')

    def test_fixed_mot(self):
        text = '-----step1:创建兼容B库，检查dolphin插件;expect:创建成功-----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} " \
                  f"dbcompatibility ='B';"
        self.log.info(sql_cmd)
        sql_res = self.commonsh.execut_db_sql(sql_cmd, dbname='postgres')
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res,
                      '执行失败' + text)

        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        sql_res = self.commonsh.execut_db_sql(sql_cmd,
                                              dbname=self.db_name)
        self.log.info(sql_res)
        self.assertIn('dolphin', sql_res, '查询失败')

        text = '-----step2:设置enable_incremental_checkpoint=off;' \
               'expect:成功-----'
        self.log.info(text)
        if 'off' not in self.default_vales:
            set_off = self.commonsh.execute_gsguc(
                "set", self.constant.GSGUC_SUCCESS_MSG,
                f'enable_incremental_checkpoint=off')
            self.log.info(set_off)
            status = self.commonsh.restart_db_cluster()
            self.log.info(status)
            res = self.common.show_param('enable_incremental_checkpoint')
            self.log.info(res)
            self.assertIn("off", res, "执行失败：" + text)

        text = '-----step3:创建mot表含fixed类型并插入数据;expect:成功-----'
        self.log.info(text)
        sql_cmd = f'''drop foreign table if exists {self.tb_name};
        create foreign table {self.tb_name}(field_name fixed(6,2));
        insert into {self.tb_name} values (9999.01);
        insert into {self.tb_name} values (1111.01);
        '''
        res = self.commonsh.execut_db_sql(sql_cmd, dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.DROP_FOREIGN_SUCCESS_MSG, res,
                      "执行失败：" + text)
        self.assertIn(self.constant.CREATE_FOREIGN_SUCCESS_MSG, res,
                      "执行失败：" + text)
        self.assertEqual(res.count(self.constant.INSERT_SUCCESS_MSG),
                         2, "执行失败：" + text)

        text = '-----step4:查询数据;expect:成功-----'
        self.log.info(text)
        res = self.commonsh.execut_db_sql(f'select * from {self.tb_name};',
                                          dbname=self.db_name)
        self.log.info(res)
        self.assertEqual('2 rows', res.splitlines()[-1].replace("(", "").
                         replace(")", ""), "执行失败" + text)

    def tearDown(self):
        text = '-----step5:恢复环境;expect:成功-----'
        self.log.info(text)
        drop_res = self.commonsh.execut_db_sql(
            f"drop database if exists {self.db_name};", dbname='postgres')
        self.log.info(drop_res)
        res = self.commonsh.execut_db_sql(
            f'show enable_incremental_checkpoint;')
        self.log.info(res)
        restores_default_value = self.commonsh.execute_gsguc(
            "set", self.constant.GSGUC_SUCCESS_MSG,
            f"enable_incremental_checkpoint={self.default_vales}")
        self.log.info(restores_default_value)
        restart_res = self.commonsh.restart_db_cluster()
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_res,
                      "执行失败：" + text)
        self.assertTrue(restores_default_value, "执行失败:" + text)
        self.assertTrue(restart_res, '执行失败:' + text)
        self.log.info(f"-----{os.path.basename(__file__)} end-----")